//
//  LoginPhoneView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 17.03.25.
//

import SwiftUI

struct LoginPhoneView: View {
    @Environment(\.presentationMode) var presentationMode;
    @Environment(\.presentToast) var presentToast
    @EnvironmentObject var appState: AppState
    
    @State var toLoginPassword:Bool = false
    @State private var phone:String = ""
    @State private var captcha:String = ""
    @State private var countDown:Int = 60
    @State var privacyChecked:Bool = false
    @State var isShowPrivacyDialog:Bool = false
    @State var showConfirmPhone:Bool = false
    // 显示验证码页面
    @State var showCaptchaView:Bool = false
    // 正在发送验证码，显示倒计时
    @State var isSendingCaptcha:Bool = false
    
    var switchLoginView:()->Void
    @State private var timer: Timer?
    @State private var timerActive: Bool = false
    
    private let maxPhoneLenght = 13
    @StateObject var viewModel = LoginPhoneViewModel()
    
    var body: some View {
        ZStack {
            VStack {
                HStack {
                    Button (action: {
                        presentationMode.wrappedValue.dismiss()
                    }) {
                        Image("koi_ic_close").padding(EdgeInsets(top: 25, leading: 45, bottom: 0, trailing: 0))
                    }
                    Spacer()
                }
                Text("手机号登录")
                    .font(.system(size: 25))
                    .bold()
                    .foregroundColor(Color.koiColorTitle)
                    .padding(EdgeInsets(top: 30, leading: 0, bottom: 0, trailing: 0))
                Text("未注册的手机号登录成功后将自动注册")
                    .font(.system(size: 13))
                    .foregroundColor(Color.koiColorTextAssist)
                    .padding(EdgeInsets(top: 5, leading: 0, bottom: 10, trailing: 0))
                VStack {
                    TextField("请输入手机号", text: $phone)
                        .padding(EdgeInsets(top: 16, leading: 25, bottom: 16, trailing: 25))
                        .background(Color.koiColorBackgroundItem)
                        .cornerRadius(40)
                        .keyboardType(.numberPad)
                        .frame(width: 272)
                        .onChange(of: phone) { value in
                            if value.count > maxPhoneLenght {
                                phone = String(value.prefix(maxPhoneLenght))
                            }
                        }
                    if showCaptchaView {
                        ZStack {
                            TextField("输入验证码", text: $captcha)
                                .padding(EdgeInsets(top: 16, leading: 25, bottom: 16, trailing: 25))
                                .background(Color.koiColorBackgroundItem)
                                .cornerRadius(40)
                                .keyboardType(.numberPad)
                                .frame(width: 272)
                            
                            HStack {
                                Spacer()
                                if isSendingCaptcha {
                                    Text(String(describing: countDown))
                                        .font(.system(size: 13))
                                        .foregroundColor(Color.koiColorTitle)
                                        .padding(.trailing , 20)
                                } else {
                                    Button(action: {
                                        sendCaptcha(phone: phone)
                                    }) {
                                        Text("重新发送")
                                            .font(.system(size: 13))
                                            .foregroundColor(Color.koiColorPrimary)
                                            .padding(.trailing , 20)
                                    }
                                }
                            }
                        }
                        .padding(.top, 10)
                    }

                    HStack {
                        Button(action:{
                            switchLoginView()
                        }) {
                            Image("koi_ic_arrow_switch")
                                .renderingMode(.template)
                                .foregroundColor(Color.koiColorTitleSecond)
                            Text("密码登录")
                                .font(.system(size: 13))
                                .foregroundColor(Color.koiColorTitleSecond)
                        }
                        Spacer()
                    }.padding(EdgeInsets(top: 5, leading: 10, bottom: 0, trailing: 0))
                }.frame(width: 272)
                    .padding(EdgeInsets(top: 20, leading: 0, bottom: 0, trailing: 0))
                Button(action:{
                    
                }) {
                    Button(action: {
                        if showCaptchaView {
                            phoneLogin()
                        } else {
                            showConfirmPhone = true
                        }
                    }) {
                        Text(showCaptchaView ? "登录" : "验证并登录")
                            .font(.system(size: 16))
                            .bold()
                            .padding(EdgeInsets(top: 16, leading: 0, bottom: 16, trailing: 0))
                            .frame(width: 272)
                            .foregroundColor(Color.white)
                            .background(Color.koiColorPrimary)
                            .cornerRadius(40)
                            .padding(.top, 20)
                            .alert("确认手机号", isPresented: $showConfirmPhone, actions: {
                                Button("取消", role: .cancel, action:{})
                                Button("确定", role: .cancel, action: {
                                    sendCaptcha(phone: phone)
                                })
                            }, message: { Text("我们将发送验证码到这个号码：\(phone)")})
                        
                    }
                }
                PrivacyCheckView(isChecked: $privacyChecked)
                Spacer()
            }
        }.koiSheet(isPresented: $isShowPrivacyDialog) {
            PrivacyConfirmDialog(
                isShowPrivacyDialog:$isShowPrivacyDialog,
                onConfirmClick: {
                    privacyChecked.toggle()
                    isShowPrivacyDialog.toggle()
                    phoneLogin()
                })
        }
        .onChange(of: viewModel.captchaState) { value in
            if value == "success" {
                viewModel.captchaState = ""
                presentToast(.init(message: "验证码已发送"))
            }
        }
        .onChange(of: viewModel.loginState) { value in
            if value == "success" {
                viewModel.loginState = ""
                appState.isLoggedIn = true
            }
        }
    }
    
    private func phoneLogin() {
        viewModel.phoneLogin(phone: phone, captcha: captcha)
    }
    
    // 发送验证码
    private func sendCaptcha(phone: String) {
        if phone.isEmpty {
            presentToast(.init(message: "请输入手机号"))
            return
        }
        
        if (!checkPrivacy()) {
            return
        }
        showCaptchaView = true
        startTimer()
        viewModel.sendCaptcha(phone: phone)
    }
    
    private func checkPrivacy() -> Bool {
        if (!privacyChecked) {
            isShowPrivacyDialog.toggle()
        }
        return privacyChecked
    }
    
    private func startTimer() {
        isSendingCaptcha = true
        countDown = 60
        timerActive = true
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
            if countDown > 0 {
                countDown -= 1
            } else {
                timer?.invalidate()
                timerActive = false
                isSendingCaptcha = false
            }
        }
    }
    
    func resetTimer() {
        timer?.invalidate()
        countDown = 60
        timerActive = false
    }
}

#Preview {
    LoginPhoneView(switchLoginView:{})
}
